package com.saer.client.button.diagnostico;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.saer.client.RemoteWebService;
import com.saer.client.RemoteWebServiceAsync;
import com.saer.client.common.Utils;
import com.saer.client.dto.diagnostico.VisitaDto;
import com.saer.client.tab.diagnostico.DiagnosticoDistanciaTab;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;

public class VisitaSearchButton extends Button {

	private final RemoteWebServiceAsync remoteWebService = GWT.create(RemoteWebService.class);
	private DiagnosticoDistanciaTab sourceTab;

	public VisitaSearchButton(DiagnosticoDistanciaTab diagnosticoDistanciaTab) {
		super("Submit");
		this.sourceTab = diagnosticoDistanciaTab;

		this.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				sourceTab.setTabTitleSuffix("");

				VisitaSearchButton.this.sourceTab.getTabCanvas().setShowHover(false);
				VisitaSearchButton.this.sourceTab.showWorkingWidget();

				remoteWebService.getVisitas(new VisitaCallBack());

			}
		});
	}

	private class VisitaCallBack implements AsyncCallback<List<VisitaDto>> {

		public void onFailure(Throwable arg0) {
			sourceTab.showErrorIcon(arg0.getMessage(), this.getClass().getName());
		}

		public void onSuccess(List<VisitaDto> result) {
			if (!validate(result)) {
				sourceTab.showErrorIcon("No hay visitas", this.getClass().getName());
			} else {
				// sourceTab.setTabTitleSuffix(" (" +
				// searchDto.getRequest().getCircuitId() + ")");

				// CfaValidationTabset sourceTabset = (CfaValidationTabset)
				// sourceTab.getPane();
				//
				// ((CfaValidationResultTab)
				// sourceTabset.getTab(1)).populateData(result);
				
				sourceTab.setData(result.get(0));

				//SectionManager.collapseBottom();

				// sourceTabset.selectTab(1);

				sourceTab.hideWorkingWidget();
			}
		}

		private boolean validate(List<VisitaDto> result) {
			if (!Utils.isEmpty(result)) {
				return true;
			}
			return false;
		}
	}
}
